import { ref, reactive } from 'vue'
import { ElMessage } from 'element-plus'
import { login, register, } from '../api/user.js' // 引入 login 和 register 方法

// 登录状态
export const isLoggedIn = ref(false)
export const currentUser = ref(null)

// 登录表单数据
export const loginForm = reactive({
    username: '',
    userpassword: ''
})

// 注册表单数据
export const registerForm = reactive({
    username: '',
    userpassword: '',
    confirmPassword: '',
    userphone: '' // 添加手机号字段
})

// 表单验证规则
export const rules = {
    username: [
        { required: true, message: '请输入用户名', trigger: 'blur' },
        { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur' }
    ],
    userpassword: [
        { required: true, message: '请输入密码', trigger: 'blur' },
        { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
    ]
}

// 登录方法
export const handleLogin = async () => {
    try {
        // 使用 login 方法发送请求到服务端验证用户信息
        const response = await login(loginForm.username, loginForm.userpassword)
        console.log('LoginForm:', loginForm);
        console.log('Response Data:', response.data);

        if (response.data.code === 1 && response.data.data) {
            isLoggedIn.value = true
            currentUser.value = response.data.data
            console.log('currentUser:', currentUser.value)
            console.log('currentUser:', currentUser.value.userid)

            ElMessage({
                type: 'success',
                message: '登录成功'
            })
            // 可以将登录状态存储到 localStorage
            localStorage.setItem('user', JSON.stringify(response.data.data))
            console.log('response.data.data',response.data.data)
        } else {
            ElMessage({
                type: 'error',
                message: response.data.msg || '用户名或密码错误'
            })
        }
    } catch (error) {
        console.error('登录失败:', error)
        ElMessage({
            type: 'error',
            message: '登录失败，请稍后重试'
        })
    }
}

// 注册方法
export const handleRegister = async () => {
    if (registerForm.userpassword !== registerForm.confirmPassword) {
        ElMessage({
            type: 'error',
            message: '两次输入的密码不一致'
        })
        return
    }

    // 创建 user 对象
    const user = {
        username: registerForm.username,
        userpassword: registerForm.userpassword,
        userphone: registerForm.userphone // 添加手机号字段
    }

    try {
        // 发送 user 对象到后端
        const response = await register(user)
        console.log('注册用户数据:', response.data); // 打印注册用户数据
        ElMessage({
            type: 'success',
            message: '注册成功'
        })
    } catch (error) {
        console.error('注册失败:', error)
        ElMessage({
            type: 'error',
            message: '注册失败，请稍后重试'
        })
    }
}

// 退出登录
export const handleLogout = () => {
    isLoggedIn.value = false
    currentUser.value = null
    localStorage.removeItem('user')
    ElMessage({
        type: 'success',
        message: '已退出登录'
    })
}

// 检查是否已登录
export const checkLoginStatus = () => {
    const savedUser = localStorage.getItem('user')
    console.log('savedUser',savedUser)
    if (savedUser) {
        currentUser.value = JSON.parse(savedUser)
        isLoggedIn.value = true
    }
}

// 获取 userid
export const getUserId = () => {
    return currentUser.value ? currentUser.value.userid : null;
}